/**
*YC 
*2017年9月1日 下午4:30:29
* <p>Description: </p> 
*/
package com.huiw.archives.common.utils.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.jdbc.Work;
import org.hibernate.service.ServiceRegistry;  

/**
 * @author YC
 *
 */
public class SessionUtil {

	Configuration conf = null;
	ServiceRegistry st = null;
	SessionFactory sf = null;
	Session sess = null;
	Transaction tx = null;

	public void HIbernateTest() {
		conf = new Configuration().configure();
		st = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
		sf = conf.buildSessionFactory(st);
		try {
			sess = sf.openSession();
			tx = sess.beginTransaction();
			// 执行Work对象指定的操作，即调用Work对象的execute()方法
			// Session会把当前使用的数据库连接传给execute()方法
			sess.doWork(new Work() {

				@Override
				public void execute(Connection arg0) throws SQLException {// 需要注意的是，不需要调用close()方法关闭这个连接
					// 通过JDBC API执行用于批量插入的sql语句
					String sql = "insert into student(name,age) values(?,?)";
					PreparedStatement ps = arg0.prepareStatement(sql);
					for (int i = 0; i < 10; i++) {
						ps.setString(1, "kobe");
						ps.setInt(2, 12);
						ps.addBatch();
					}
					ps.executeBatch();
				}
			});
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
		} finally {
			sess.close();
			sf.close();
		}
	}

	public static void main(String[] args) {
		new SessionUtil().HIbernateTest();
	}

}
